package com.szy.controller;

import com.github.pagehelper.PageInfo;
import com.szy.pojo.Article;
import com.szy.pojo.Category;
import com.szy.pojo.User;
import com.szy.service.ArticleService;
import com.szy.service.CategoryService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpSession;
import java.util.List;

@Controller
@RequestMapping("/article")
public class ArticleController {

    @Autowired
    private CategoryService categoryService;

    @Autowired
    private ArticleService articleService;

    @RequestMapping("/index/{pageNum}")
    public String index(Model model,
                        @PathVariable(name = "pageNum") int pageNum){
        PageInfo<Article> pageInfo = articleService.queryAllAndAuthor(pageNum);
        for(Article article : pageInfo.getList()){
            System.out.println(article.getArticleCreateTime());
        }
        List<Category> categories = categoryService.queryAll();
        model.addAttribute("categories", categories);
        model.addAttribute("pageInfo", pageInfo);
        return "/article/index";
    }

    @RequestMapping("/publish")
    public void publish(){}

    @ResponseBody
    @PostMapping("/addArticle")
    public String addArticle(Article article, HttpSession session){
        User user = (User) session.getAttribute("user");
        article.setArticleUserId(user.getId());
        articleService.addArticle(article);
        return "OK";
    }

    @RequestMapping("/articleDetail/{articleID}")
    public String showArticle(Model model,@PathVariable int articleID){
        Article article = articleService.queryArticleAndAuthor(articleID);
        model.addAttribute("article", article);

        List<Category> categories = categoryService.queryAll();
        model.addAttribute("categories", categories);
        return "/article/articleDetail";
    }

    @ResponseBody
    @RequestMapping("/popularArticles")
    public List<Article> popularArticles(){
        List<Article> articles = articleService.popularArticles();
        return articles;
    }

    @RequestMapping("/queryNewestArticle")
    public String queryNewestArticle(Model model){
        Article article = articleService.queryNewestArticle();
        model.addAttribute("article", article);

        List<Category> categories = categoryService.queryAll();
        model.addAttribute("categories", categories);
        return "/article/articleDetail";
    }

}
